﻿using System;
using System.Linq;
using System.Windows.Forms;
using QFlow.Data;
using System.Resources;

namespace QFlow.Windows.Forms
{
    public partial class NewRole : Utils.BaseForm
    {
        bool _New, _Loaded;
        Role _Role;

        public NewRole(bool dialog, QFlowDbContext context)
            : base(context)
        {
            InitializeComponent();
            _New = true;
            _Role = null;
        }

        public NewRole(int roleId, QFlowDbContext context)
            : base(context)
        {
            InitializeComponent();
            btnCancel.Visible = true;
            _New = false;
            this.Text = QFlow.Windows.Properties.Resources.FRMEditRole;

            _Role = this.Context.Roles.SingleOrDefault(r => r.RoleID == roleId);
            txtRoleName.Text = _Role.RoleName;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (superValidator1.Validate())
            {
                try
                {
                    if (_New)
                    {
                        Role role = new Role();
                        role.RoleName = txtRoleName.Text;

                        foreach (DataGridViewRow row in gvPermissions.Rows)
                        {
                            if (row.Cells[0].Value != null)
                            {
                                bool value = Convert.ToBoolean(row.Cells[0].Value);
                                if (value)
                                    role.RolePermissions.Add(new RolePermission { PermissionID = (row.DataBoundItem as Permission).PermissionID, RoleID = 0 });

                            }
                        }

                        this.Context.Roles.InsertOnSubmit(role);
                        this.Context.SubmitChanges();
                    }
                    else
                    {
                        _Role.RoleName = txtRoleName.Text;

                        foreach (DataGridViewRow row in gvPermissions.Rows)
                        {

                            bool value = Convert.ToBoolean(row.Cells[0].Value);
                            if (value)
                            {
                                if (_Role.RolePermissions.SingleOrDefault(perm => perm.PermissionID == (row.DataBoundItem as Permission).PermissionID && perm.RoleID == _Role.RoleID) == null)
                                    _Role.RolePermissions.Add(new RolePermission { PermissionID = (row.DataBoundItem as Permission).PermissionID, RoleID = _Role.RoleID });
                            }
                            else
                            {
                                RolePermission rolePerm = _Role.RolePermissions.SingleOrDefault(perm => perm.PermissionID == (row.DataBoundItem as Permission).PermissionID);
                                if (rolePerm != null)
                                {
                                    this.Context.RolePermissions.DeleteOnSubmit(rolePerm);
                                }
                            }
                        }

                        this.Context.SubmitChanges();
                    }
                    PostSave();
                }
                catch
                {
                    MessageBox.Show(QFlow.Windows.Properties.Resources.MBCantSaveChanges, QFlow.Windows.Properties.Resources.MBErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                }
            }
        }

        private void PostSave()
        {
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void NewRole_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.txtRoleName.CausesValidation)
            {
                this.txtRoleName.CausesValidation = false;
                this.Close();
            }
        }

        private void NewRole_Load(object sender, EventArgs e)
        {
            _Loaded = true;
            PermissionBindingSource.DataSource = this.Context.Permissions.ToArray();
        }

        private void gvPermissions_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (_Loaded)
            {
                if (_Role != null)
                {
                    foreach (DataGridViewRow row in gvPermissions.Rows)
                    {
                        int permissionId = (row.DataBoundItem as Permission).PermissionID;
                        if (_Role.RolePermissions.SingleOrDefault(perm => perm.PermissionID == permissionId) != null)
                            row.Cells[0].Value = true;
                    }
                }
            }
        }

        private void gvPermissions_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                ResourceManager manager = new ResourceManager("QFlow.Windows.Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());
                DataGridViewRow row = gvPermissions.Rows[e.RowIndex];
                e.Value = manager.GetString((row.DataBoundItem as Permission).PermissionName + "Perm");
            }
        }
    }
}
